import { LoginService } from '@service/login.service';
import { Router, ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';

import { Injectable } from '@angular/core';
import {
	HttpRequest,
	HttpHandler,
	HttpEvent,
	HttpResponse,
	HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError as _throw, of } from 'rxjs';
import { tap, mergeMap, finalize, catchError } from 'rxjs/operators';
import { HttpCacheService } from './http-cache.service';
import { TOKEN } from '@app/store/dict';
// import * as NProgress from 'nprogress';
const whiteList = ['/login', '/password', '/qrcode'];
/**
 * @export 返回拦截器类
 */
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
	warningModal;
	constructor(
		private nzMessageService: NzMessageService,
		private httpCacheService: HttpCacheService,
		private nzModalService: NzModalService,
		private router: Router,
		private loginService: LoginService
	) {}
	intercept = (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> => {
		// NProgress.start(); // 显示顶部加载进度条
		/* 设置全局的请求头 */
		const token = this.httpCacheService.getSessionCache(TOKEN);
		const newReq = req.clone({
			setHeaders: { ['token']: token }
		});
		return next.handle(newReq).pipe(
			tap((res: any) => {
			}),
			mergeMap((event: any) => {
				if (event instanceof HttpResponse
					&& (event.body?.code === 500 || event.body?.code === 401)
					&& !whiteList.some(url => event.url.includes(url))
					) {
					return Observable.create(observer => observer.error(event));
				}
				// if (event instanceof HttpResponse) {
				//   NProgress.done();
				// }
				return of(event);
			}),
			catchError((res: HttpResponse<any>) => {
				// NProgress.done();
				switch (res.body?.code) {
					case 401:
						// 拦截到401错误
						// window.top.location.reload(); // 刷新最外层页面
						if (this.warningModal) {
							return;
						}
						this.warningModal = this.nzModalService.info({
							nzTitle: '权限验证失败',
							nzContent: res.body.msg,
							nzOkText: '去登录',
							nzOnOk: () => {
								const url = location.hash.replace(/#/g, '') || '';
								this.router.navigate(['/login'], { queryParams: { redirectUrl: url } });
								this.warningModal = null;
								this.loginService.clearUserInfo();
							},
							nzOnCancel: () =>{
								// console.log('789');
								this.warningModal = null;
							}
								
						});
						break;
					case 200:
						// 业务层级错误处理
						if (res.body.msg) {
							// const params = req.method === 'POST' ? JSON.stringify(req.body) : null;
							this.nzMessageService.error(res.body.msg);
						}
						break;
					case 404:

						break;
					case 500:
						if (res.body.msg) {
							this.nzMessageService.error(res.body.msg);
						}
						break;
					default:

						break;
				}
				return _throw(res);
			}),
			finalize(() => {

			})
		) as Observable<HttpEvent<any>>;
	}
}

